package com.zc.gateway.security.config;

import com.zc.gateway.security.filter.AuthenticationCheckFilter;
import com.zc.gateway.security.filter.LoginRequestFilter;
import com.zc.gateway.security.handler.LoginFailedHandler;
import com.zc.gateway.security.handler.LoginSuccessHandler;
import com.zc.gateway.security.handler.RoleAccessDeniedHandler;
import com.zc.gateway.security.manager.LoginAuthenticationManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity;
import org.springframework.security.config.web.server.SecurityWebFiltersOrder;
import org.springframework.security.config.web.server.ServerHttpSecurity;
import org.springframework.security.web.server.SecurityWebFilterChain;

/**
 * web安全配置
 *
 * @author zcj
 * @version 1.0.0
 * @date 2022/1/6 15:01
 */
@EnableWebFluxSecurity
public class WebSecurityConfig {

    @Autowired
    private LoginSuccessHandler loginSuccessHandler;
    @Autowired
    private LoginFailedHandler loginFailedHandler;
    @Autowired
    private AuthenticationCheckFilter authenticationCheckFilter;
    @Autowired
    private LoginRequestFilter loginRequestFilter;
    @Autowired
    private RoleAccessDeniedHandler roleAccessDeniedHandler;
    @Autowired
    private LoginAuthenticationManager loginAuthenticationManager;


    @Bean
    public SecurityWebFilterChain webfluxWebFilterChain(ServerHttpSecurity http) {
        ServerHttpSecurity.FormLoginSpec loginSpec = http.formLogin();
        return loginSpec
                .loginPage("/login")
                .authenticationManager(loginAuthenticationManager)
                .authenticationSuccessHandler(loginSuccessHandler)
                .authenticationFailureHandler(loginFailedHandler)
                .and()
                .cors()
                .and()
                .csrf().disable()
                .authorizeExchange()
                .anyExchange().authenticated()
                .and()
                .exceptionHandling().accessDeniedHandler(roleAccessDeniedHandler)
                .and()
                .addFilterAt(loginRequestFilter, SecurityWebFiltersOrder.FORM_LOGIN)
                .addFilterAt(authenticationCheckFilter, SecurityWebFiltersOrder.AUTHORIZATION)
                .build();
    }
}
